// pages/updataUserInfo/updataUserInfo.js
var app = getApp()
Page({
  data: {
    image: "",
    name: "微信用户",
    nameJud: true,
    imageUpdataJud: false,
    openid: "",
    evaluate: [],
    userInfo: {
      image: "",
      name: "微信用户",
      openid: ""
    }
  },
  onLoad(options) {
    let name = wx.getStorageSync('userInfo').name
    if (name == "微信用户") {
      this.setData({
        openid: options.openid,
        image: wx.getStorageSync('userInfo').image,
        name: name
      })
    } else {
      this.setData({
        openid: options.openid,
        image: wx.getStorageSync('userInfo').image,
        name: name,
        nameJud: false
      })
    }

  },
  onChooseAvatar(e) {
    this.setData({
      image: e.detail.avatarUrl,
      imageUpdataJud: true
    })
  },
  updataName(e) {
    this.data.name = e.detail.value
  },
  saveUserInfo() {
    let that = this
    var newDateTime = Date.parse(new Date())
    let image = wx.getStorageSync('userInfo').image
    let imageUrl = 'user_image/' + wx.getStorageSync('userInfo').openid + newDateTime + '.jpeg'
    if (this.data.imageUpdataJud) {
      wx.cloud.deleteFile({
        fileList: [image],
        success: res => {
          // handle success
          console.log(res.fileList)
        },
        fail: console.error
      })
    }
    wx.cloud.uploadFile({
        // 指定上传到的云路径
        cloudPath: imageUrl,
        // 指定要上传的文件的小程序临时文件路径
        filePath: this.data.image
      })
      .then(res => {
        that.data.image = res.fileID
        if (that.data.name == "") {
          that.data.name = "微信用户"
        }
        that.setData({
          userInfo: {
            image: that.data.image,
            name: that.data.name,
            openid: that.data.openid
          }
        })
        wx.setStorageSync('userInfo', that.data.userInfo)
        that.updataEvaluateUserInfo()
        wx.showToast({
          title: '保存成功',
          icon: 'none'
        })
        console.log("成功")
      })
      .catch(err => {
        that.setData({
          userInfo: {
            image: that.data.image,
            name: that.data.name,
            openid: that.data.openid
          }
        })
        wx.setStorageSync('userInfo', that.data.userInfo)
        that.updataEvaluateUserInfo()
        wx.showToast({
          title: '保存成功',
          icon: 'none'
        })
      })
    this.data.imageUpdataJud = false
  },
  updataEvaluateUserInfo() {
    wx.cloud.callFunction({
        // 云函数名称
        name: 'updataEvaluateUserInfo',
        // 传给云函数的参数
        data: {
          image: wx.getStorageSync('userInfo').image,
          name: wx.getStorageSync('userInfo').name
        },
      })
      .then(res => {
        console.log(res)
      })
      .catch(console.error)
  }
})